package com.daigou.sg

import com.yutianran.springBoot.decorator.Decorator
import org.junit.Test

/**
 * Example local unit test, which will execute on the development machine (host).
 *
 * @see [Testing documentation](http://d.android.com/tools/testing)
 */
class FunTest {
    /**
     * 函数式编程三板斧
     * 1.Map:K -> V 映射
     * 2.Reduce:S,T -> S 合并
     * 3.Filter:Boolean  过滤
     */
    @Test
    fun testMapReduce() {
        //计算数组中正数的平均值
        val num = listOf(2, -5, 9, 7, -2, 5, 3, 1, 0, -3, 8)
        val positive_num = num.filter { it > 0 }
        val average = num.reduce { x, y -> x + y } / positive_num.size
        println(average)

        //将一首藏头诗的每句诗的第一句拿出来拼成一句话
        val texts = arrayOf("芦花丛中一扁舟", "俊杰俄从此地游", "义士若能知此理", "反躬难逃可无忧")
        val result = texts.map { it.substring(0, 1) }.reduce { r, s -> "$r$s" }
        println(result)

        //求最大元素
        val max = num.reduce { acc, i -> if (acc > i) acc else i }
        println(max)
    }

    @Test
    fun testDecorator() {
        //通过::可以获取一个类的函数引用
        val f = ::hello as Function1<String, Unit>
        //可以将这个函数作为参数传给另一个函数，作为装饰者模式
        decorator(f, "kotlin")
    }

    fun <P1> decorator(function: Function1<P1, Unit>, t: P1): Function1<P1, Unit> {
        println("Before")
        function.invoke(t)
        println("After")
        return function
    }

    /**
     * 实质是一个函数对象Function1<String,Unit>
     */
    fun hello(str: String): Unit {
        println("hello," + str)
    }
}